package com.cloudptt.wp.ui.more;

import java.util.Timer;
import java.util.TimerTask;

import com.cloudptt.api.comm.CauseCont;
import com.cloudptt.api.comm.CommDlg;
import com.cloudptt.api.models.ErrInfo;
import com.cloudptt.api.product.Product;
import com.cloudptt.api.product.ProductConst;
import com.cloudptt.api.product.func.sys.listener.SysMsgListener;
import com.cloudptt.api.product.log.Log;
import com.cloudptt.api.product.operator.SysOperator;
import com.cloudptt.wp.R;
import com.cloudptt.wp.SysApplication;
import com.cloudptt.wp.ui.Login;
import com.cloudptt.wp.ui.dlg.UiDlg;
import com.mcptt.config.local.SysConfig;

import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.EditText;
import android.widget.TextView;

public class ChPwd extends Activity {

	private final static String THIS_FILE = "ChPwd";

	private TextView backView;
	private EditText nameEdit;
	private EditText oldPwdEdit;
	private EditText newPwdEdit;
	private EditText rePwdEdit;

	private SharedPreferences sharedPreferences;
	private Timer ticktimer;
	private Handler handler;
	private Dialog progressBar;
	private boolean visableflag = false;

	private SysConfig sysConfig = null;

//	private SysOperator operator = null;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.chpwd);

		this.nameEdit = (EditText) findViewById(R.id.nameEditText);
		this.oldPwdEdit = (EditText) findViewById(R.id.oldPasswordEditText);
		this.newPwdEdit = (EditText) findViewById(R.id.newPasswordEditText);
		this.rePwdEdit = (EditText) findViewById(R.id.repasswordEditText);

		SysApplication app = ((SysApplication) getApplicationContext());
		Product product = app.getProduct();
		this.sysConfig = product.getSysConfig();

//		sharedPreferences = this.getSharedPreferences(
//				Const.SHARED_SECTION_USERINFO, Context.MODE_WORLD_READABLE);
//		String username = sharedPreferences.getString(
//				Const.SHARED_PROP_USERNAME, "");
		String userName = this.sysConfig.getMcInfo().getName();
		this.nameEdit.setText(userName);
		if (userName.equals("")) {
			this.nameEdit.setEnabled(true);
		} else {
			this.nameEdit.setEnabled(false);
		}

		TextView modifyBtn = (TextView) findViewById(R.id.modifyPwd);
		modifyBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				modify_pwd(v);
			}

		});
		backView = (TextView ) findViewById(R.id.return_bt);
		backView.setOnTouchListener(new OnTouchListener() {
			public boolean onTouch(View v, MotionEvent event) {
				ChPwd.this.finish();
				return false;
			}
		});

		initHandler();
	}

	public void modify_back(View v) {
		this.finish();
	}

	public void modify_pwd(View v) {
		if (checkData()) {
			doReportRegisterInfoAction();
			showWaitCover(true,null);
			startTickTimerCheck();
		}
	}

	private boolean checkData() {
		String orgPwd = this.oldPwdEdit.getText().toString().trim();
		String pwd = this.newPwdEdit.getText().toString().trim();
		String rePwd = this.rePwdEdit.getText().toString().trim();
		String oldPwd = this.sysConfig.getMcInfo().getPwd();

//		String oldPwd = sharedPreferences.getString(Const.SHARED_PROP_PASSWORD,
//				"");
//		if (!oldPwd.equals(orgPwd)) {
//			CommDlg.show(this, "原密码不正确");
//			return false;
//		}
		if ( orgPwd.equals("") || pwd.equals("") || rePwd.equals("")) {
			CommDlg.show(this, getResources().getString(R.string.invalid_password));
			return false;
		}
		if (!pwd.equals(rePwd)) {
			CommDlg.show(this, getResources().getString(R.string.confirm_new_password));
			return false;
		}
		if ( pwd.length()<6) {
			CommDlg.show(this, getResources().getString(R.string.password_requirement));
			return false;
		}

		return true;
	}

	public void doReportRegisterInfoAction() {

		String oldPwd = this.oldPwdEdit.getText().toString().trim();
		String pwd = this.newPwdEdit.getText().toString().trim();

		SysApplication app = ((SysApplication)getApplicationContext());
		Product product = app.getProduct();
//		product.setSysMsgListener(ChPwd.this);

		SysOperator operator = (SysOperator)product.getOperator(ProductConst.Func_Sys);
		if(operator != null)
		{
//			try 
//			{
////				operator.sendChPwdSysMsg(oldPwd, pwd);
//			} catch (RemoteException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
		}
		else
		{
			Message msg = new Message();
			msg.what = 1;
			msg.obj = getString(R.string.fail);
			handler.sendMessage(msg);
		}

	}

	private void success() {
		if (null != ticktimer) {
			ticktimer.cancel();
			ticktimer = null;
		}
		// save new password
//		SharedPreferences.Editor editor = sharedPreferences.edit();
//		editor.putString(Const.SHARED_PROP_PASSWORD, "");
//		editor.putBoolean(Const.SHARED_PROP_AUTOLOGIN, false);
//		editor.commit();

		SysApplication app = ((SysApplication)getApplicationContext());
		Product product = app.getProduct();
		product.doLogout();

		DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener()
		{
			@Override
			public void onClick(DialogInterface dialog, int which)
			{
				ChPwd.this.finish();
				goToLogin();
			}
		};
		CommDlg.showWarrningDlg(ChPwd.this, getString(R.string.success), listener);
	}

	private void goToLogin()
	{
		Intent intent = new Intent();
		intent.setClass(ChPwd.this,Login.class);
		intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		startActivity(intent);
	}

	protected void initHandler() {
		handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				super.handleMessage(msg);
				switch (msg.what) {

					case 1:
						showWaitCover(false, null);
						CommDlg.show(getApplicationContext(), (String)msg.obj);

						break;
					case 2:
						showWaitCover(false, null);
						CommDlg.show(getApplicationContext(), (String)msg.obj);
						break;
					default:
						showWaitCover(false, null);
						break;
				}
			}
		};
	}

	private void startTickTimerCheck() {
		ticktimer = new Timer("ticktimer");
		TimerTask tt = new TimerTask() {
			@Override
			public void run() {
				if (visableflag) {
					Message msg = new Message();
					msg.what = 1;
					msg.obj = getString(R.string.fail);
					handler.sendMessage(msg);
				}
			}
		};

		ticktimer.schedule(tt, 5000);
	}

	private void showWaitCover(final boolean show, String content) {
		if (show) {
//			progressBar.setVisibility(View.VISIBLE);
			visableflag = true;
			progressBar = UiDlg.createLoadingDialog(ChPwd.this,
					getString(R.string.please_wait));
			progressBar.show();
		} else {
//			progressBar.setVisibility(View.GONE);
			progressBar.dismiss();
			visableflag = false;
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}

//	private ISipService service;
//	private ServiceConnection connection = new ServiceConnection() {
//		@Override
//		public void onServiceConnected(ComponentName arg0, IBinder arg1) {
//			service = ISipService.Stub.asInterface(arg1);
//		}
//
//		@Override
//		public void onServiceDisconnected(ComponentName arg0) {
//			service = null;
//		}
//	};

//	private ChPwd.BaseReceiver receiver = null;
//
//	private void startReceiver() {
//		if (null == receiver) {
//			IntentFilter filter = new IntentFilter();
//			filter.addAction(SipManager.ACTION_SIP_MESSAGE_RECEIVED);
//			receiver = new ChPwd.BaseReceiver();
//			this.registerReceiver(receiver, filter);
//		}
//	}
//
//	private void stopReceiver() {
//		if (null != receiver) {
//			unregisterReceiver(receiver);
//			receiver = null;
//		}
//	}
//
//	public class BaseReceiver extends BroadcastReceiver {
//		public void onReceive(Context context, Intent intent) {
//			if (intent.getAction().equals(
//					SipManager.ACTION_SIP_MESSAGE_RECEIVED)) {
//				int type = intent.getIntExtra(XMLUtil.MSG_TYPE, 100);
//				if (type != XMLUtil.Type_ChPwd) {
//					return;
//				}
//
//				String status = intent.getStringExtra(XMLUtil.MSG_STATUS);
//				Log.d("ChPwd", "status=" + status );
//				Message msg = new Message();
//				stopReceiver();
//				if (null != ticktimer) {
//					ticktimer.cancel();
//					ticktimer = null;
//				}
//				if( !status.equals("0") )
//				{
//					Log.d(THIS_FILE, "status="+status);
//					msg.what = 1;
//					ErrInfo errInfo = new ErrInfo(CauseCont.ERROR_TITLE_CHPWD, CheckData.parseInt(status), context);
//					msg.obj = errInfo != null ? errInfo.getErrDesc() : "";
//					handler.sendMessage(msg);
//					return;
//				}
//				SharedPreferences.Editor editor = sharedPreferences.edit();
//				editor.putString(Const.SHARED_PROP_PASSWORD, newPwdEdit
//						.getText().toString().trim());
//				editor.commit();
//				
//				msg.what = 3;
//				msg.obj = getString(R.string.success);
//				handler.sendMessage(msg);
//				
//				success();
//			}
//
//		}
//	}

	//	@Override
//	public void onChPwd(int result) {
//		// TODO Auto-generated method stub
//
//		if (null != ticktimer) {
//			ticktimer.cancel();
//			ticktimer = null;
//		}
//		if( result != 0 )
//		{
//			Log.d(THIS_FILE, "result="+result);
//			Message msg = new Message();
//			msg.what = 1;
//			ErrInfo errInfo = new ErrInfo(CauseCont.ERROR_TITLE_CHPWD, result);
//			msg.obj = errInfo != null ? errInfo.getErrDesc() : "";
//			handler.sendMessage(msg);
//			return;
//		}
//
//		String pwd = newPwdEdit.getText().toString();//.trim()
//		this.sysConfig.setPwdAfterChgPwd(pwd);
//
//		Message msg = new Message();
//		msg.what = 3;
//		msg.obj = getString(R.string.success);
//		handler.sendMessage(msg);
//
//		success();
//	}
//	@Override
//	public void receiveSysMsg(String type)
//	{}
}
